<?php
/**
 * Created by PhpStorm.
 * User: cgx
 * Date: 2016/8/8
 * Time: 10:12
 */

namespace spider\Controller;
use Think\Controller;
use QL\QueryList;
use Sunra\PhpSimple\HtmlDomParser;
set_time_limit(0);
error_reporting(0);

class HuyaController extends Controller{

    public function index(){
        $start_time = time();

        $game_type = C('HUYA_GAME');
        $page = 1;
        $top_views = 100;

        $is_update = true;
        while ($page<5){
            $huya_api = sprintf(C('HUYA_API'),$page);
            echo $huya_api;
            //获取json
            $response = QueryList::Query($huya_api,array('html'=>'html'))->html;
            if($response && strlen($response) != 0){
                $res_arr = json_decode($response,true);
                $res_list = $res_arr['data']['list'];
                //遍历json数组
                foreach ($res_list as $k => $v){
                    $game_host_name = $v['gid'];
                    if(!array_key_exists($game_host_name,$game_type)){
                        continue;
                    }
                    $views = intval($v['totalCount']);
                    if($views<$top_views){
                        continue;
                    }


                    $kw['title'] = $v['introduction'];
                    $kw['thumb'] = $v['screenshot'];
                    $kw['keywords'] ='';
                    $kw['description'] = '';
                    $kw['inputtime'] = time();
                    $kw['updatetime'] = time();
                    $kw['zb_thumb'] = $v['avatar180'];
                    $kw['zbid'] = $v['privateHost'];
                    $kw['zbname'] = $v['nick'];
                    $kw['source'] = 'huya';
                    $kw['category'] = $game_type[$game_host_name];
                    $kw['isOnlive'] = '1';
                    $kw['livedata'] = $this->get_zb_room_str($v['privateHost']);
                    $kw['m_livedata'] = '';
                    $kw['views'] = $views;
                    if($is_update){
                        befor_update('huya');
                        update_zhibo('huya',$kw);
                        $is_update=false;
                    }else{
                        update_zhibo('huya',$kw);
                    }
                    
                }

            }
            $page +=1;
        }





        echo 'time cost '.(time()-$start_time).' seconds';


    }


    private function get_zb_room_str($id){
//        $id='kaerlol';
        $url = sprintf(C('HUYA_VIEW'),$id);
        $html = HtmlDomParser::file_get_html($url);
        if($html==false){
            $livedata='';
        }else{
            $livedata_arr = $html->find('#flash-link','0')->attr;
            $livedata = $livedata_arr['value'];
            $html->clear();
        }
        return $livedata;


    }





}